package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Dish;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.Setmeal;
import com.sky.mapper.OrderDetailsMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailsMapper detailsMapper;

    @Autowired
    private UserMapper userMapper;

    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dates = new ArrayList<>();

        dates.add(begin);

        while (!begin.isEqual(end)) {
            begin = begin.plusDays(1);
            dates.add(begin);
        }

        List<Double> turnovers = new ArrayList<>();

        for (LocalDate date : dates) {
            Map<String, Object> map = new HashMap<>();

            map.put("begin", LocalDateTime.of(date, LocalTime.MIN));
            map.put("end", LocalDateTime.of(date, LocalTime.MAX));
            map.put("status", Orders.COMPLETED);

            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnovers.add(turnover);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dates, ","))
                .turnoverList(StringUtils.join(turnovers, ","))
                .build();
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dates = new ArrayList<>();

        dates.add(begin);

        while (!begin.isEqual(end)) {
            begin = begin.plusDays(1);
            dates.add(begin);
        }

        List<Integer> totalUserList = new ArrayList();
        List<Integer> newUserList = new ArrayList();

        for (LocalDate date : dates) {
            LocalDateTime beginDate = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endDate = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("end", endDate);
            Integer totalUser = userMapper.getUserStatistics(map);
            totalUser = totalUser == null ? 0 : totalUser;
            totalUserList.add(totalUser);
            map.put("begin", beginDate);
            Integer newUser = userMapper.getUserStatistics(map);
            newUser = newUser == null ? 0 : newUser;
            newUserList.add(newUser);
        }
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dates, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> dates = new ArrayList<>();

        dates.add(begin);

        while (!begin.isEqual(end)) {
            begin = begin.plusDays(1);
            dates.add(begin);
        }

        List<Integer> totalOrderList = new ArrayList();
        List<Integer> validOrderList = new ArrayList();


        for (LocalDate date : dates) {
            Map<String, Object> map = new HashMap<>();

            map.put("begin", LocalDateTime.of(date, LocalTime.MIN));
            map.put("end", LocalDateTime.of(date, LocalTime.MAX));

            Integer totalOrder = orderMapper.getOrderStatistics(map);
            totalOrderList.add(totalOrder);

            map.put("status", Orders.COMPLETED);
            Integer validOrder = orderMapper.getOrderStatistics(map);
            validOrderList.add(validOrder);
        }

/*        Map<String, Object> map = new HashMap<>();
        map.put("begin",LocalDateTime.of(dates.get(0),LocalTime.MIN));
        map.put("end",LocalDateTime.of(dates.get(dates.size() - 1),LocalTime.MAX));
        Integer totalOrderCount = orderMapper.getOrderStatistics(map);

        map.put("status", Orders.COMPLETED);
        Integer validOrderCount = orderMapper.getOrderStatistics(map);*/

        Integer totalOrderCount = totalOrderList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderList.stream().reduce(Integer::sum).get();

        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dates, ","))
                .validOrderCountList(StringUtils.join(validOrderList, ","))
                .orderCountList(StringUtils.join(totalOrderList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {

        LocalDateTime beginDate = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endDate = LocalDateTime.of(end, LocalTime.MAX);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("begin", beginDate);
        hashMap.put("end", endDate);
        hashMap.put("status", Orders.COMPLETED);

        List<GoodsSalesDTO> list = orderMapper.selectForSalesTop10(hashMap);

        List<String> nameList = list.stream().map(GoodsSalesDTO::getName).toList();
        List<Integer> numberList = list.stream().map(GoodsSalesDTO::getNumber).toList();

/*
        List<Orders> orderList = new ArrayList<>();

        orderList = orderMapper.selectForSalesTop10(hashMap);

        TreeMap<String, Integer> map = new TreeMap();

        for (Orders order : orderList) {
            List<OrderDetail> orderDetailList = detailsMapper.getByOrderId(order);
            for (OrderDetail orderDetail : orderDetailList) {
                if (orderDetail.getDishId() == null) {
                    Setmeal setmeal = detailsMapper.getSetmeal(orderDetail);
                    if (map.containsKey(setmeal.getName())) {
                        map.put(setmeal.getName(), orderDetail.getNumber() + map.get(setmeal.getName()));
                    }
                    map.put(setmeal.getName(), orderDetail.getNumber());
                }
                Dish dish = detailsMapper.getDish(orderDetail);
                if (map.containsKey(dish.getName())) {
                    map.put(dish.getName(), orderDetail.getNumber() + map.get(dish.getName()));
                }
                map.put(dish.getName(), orderDetail.getNumber());
            }
        }

        Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
        LinkedList<Map.Entry<String, Integer>> entryLinkedList = new LinkedList<>(entrySet);
        Collections.sort(entryLinkedList, (o1, o2) -> o2.getValue().compareTo(o1.getValue()));
        map.clear();
        for (Map.Entry<String, Integer> entry : entryLinkedList) {
            map.put(entry.getKey(),entry.getValue());
        }

                Set<String> keySet = map.keySet();
        Collection<Integer> values = map.values();
        */

        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }
}
